package be.scond.cartpool.API;

import java.util.List;

import javax.jdo.JDOObjectNotFoundException;
import javax.jdo.PersistenceManager;

import be.scond.cartpool.exceptions.GroupDoesNotExistException;
import be.scond.cartpool.exceptions.UserNotFoundException;
import be.scond.cartpool.exceptions.WrongPasswordException;
import be.scond.cartpool.model.Group;
import be.scond.cartpool.model.User;
import be.scond.utils.PMF;

import com.google.appengine.api.datastore.Key;
import com.google.appengine.api.datastore.KeyFactory;

public class UserApi {

	
	public static User confirmUser(String email, String groupName) throws UserNotFoundException {
		PersistenceManager pm = PMF.get().getPersistenceManager();
        try{
        	User u = getUser(pm, email, groupName);
        	u.setConfirmed(true);
        	pm.close();        	        	
        	return u;
        } catch (UserNotFoundException e){
        	throw e;
        }
	}
	
	public static User getUser(PersistenceManager pm, String email, String groupName) throws UserNotFoundException {
		email = email.toLowerCase();
		groupName = groupName.toLowerCase();
		Key key = new KeyFactory.Builder(Group.class.getSimpleName(), groupName).addChild(User.class.getSimpleName(), email).getKey();
		try{
			User u = pm.getObjectById(User.class, key);
			return u;
		} catch (JDOObjectNotFoundException e){
			throw new UserNotFoundException();
		}
	}	
	
	public static void deleteUser(String key) throws UserNotFoundException {
		PersistenceManager pm = PMF.get().getPersistenceManager();		
		try{
			User u = pm.getObjectById(User.class, key);
			pm.deletePersistent(u);
        	pm.close();
        } catch (JDOObjectNotFoundException e){
			throw new UserNotFoundException();
		}
	}
	
	public static User login(String email, String groupName, String password) throws UserNotFoundException, WrongPasswordException {
		PersistenceManager pm = PMF.get().getPersistenceManager();
		try{
			email = email.toLowerCase();
			groupName = groupName.toLowerCase();
			User u = getUser(pm, email, groupName);
			String pass = u.getPassword();
			pm.close();
			if(pass.equals(password)){
				return u;
			}else{
				throw new WrongPasswordException();
			}
		} catch (UserNotFoundException e){
			throw e;
		}
	}	
	
	public static List<User> getAllUsers(String groupName) throws GroupDoesNotExistException {
		PersistenceManager pm = PMF.get().getPersistenceManager();
		try {
			Group g = GroupApi.getGroup(pm, groupName);
			List<User> users = g.getUsers();
			String dummy = "";
			for (User user : users) {
				dummy += user.toXmlString();
			}	
			pm.close();
			return users;
		} catch (GroupDoesNotExistException e) {
			throw e;
		}
		
	}
}